<?php

namespace App\Admin\Controllers;

use DB;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use App\WxGroup;

class WxController extends Controller
{
	/**
	 * 群列表
	 */
	public function groupList(Request $request) 
	{
		$groups = WxGroup::where('id', '!=', 0);
		$groups = $groups->paginate(15);
		return view('admin.group.list', compact('groups'));
	}

	/**
	 * 新增群
	 */
	public function create()
	{
		$token = $this->generate_token();
		return view('admin.group.create', compact('token'));
	}

	/**
	 * 保存
	 */
	public function store(Request $request)
	{
        $validator = Validator::make($request->all(), [
			'group_token' => 'required|unique:wx_group',
			'robot' => 'required'
        ], [
        	'group_token.required' => 'token不能为空',
        	'robot.required' => '请填写助手在群内名称'
        	]);

        if ($validator->passes()) {
        	$group = new WxGroup;
        	$group->group_token = $request->input('group_token');
        	$group->robot = $request->input('robot');
        	$group->save();

			return ['flag' => true, 'msg' => '创建成功'];
        } else {
        	return $validator->errors();
        }
	}


	/**
	 * 生成token
	 */
	protected function generate_token( $length = 16 ) { 
		// 密码字符集，可任意添加你需要的字符 
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; 
		$password = ''; 
		for ( $i = 0; $i < $length; $i++ ) 
		{ 
			// 这里提供两种字符获取方式 
			// 第一种是使用 substr 截取$chars中的任意一位字符； 
			// 第二种是取字符数组 $chars 的任意元素 
			// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); 
			$password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; 
		} 
		return $password; 
	} 

}	